﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace ArienToolkits.DBUntilities.SqlServer.Extension
{
    /// <summary>
    /// SqlServer参数扩展类
    /// </summary>
    public static class ParameterExtionsion
    {
        /// <summary>
        /// 转换为输入参数
        /// </summary>
        /// <param name="obj">转换对象源</param>
        /// <param name="parameterName">参数名称</param>
        /// <returns></returns>
        public static SqlParameter ToInParam(this object obj, string parameterName)
        {
            parameterName = parameterName.StartsWith("@") ? parameterName : "@" + parameterName;

            if (obj == null)
            {
                obj = System.DBNull.Value;
            }

            return new SqlParameter(parameterName, obj);
        }

        /// <summary>
        /// 构建新的输出参数
        /// </summary>
        /// <param name="parameterName">参数名称</param>
        /// <param name="type">参数类型</param>
        /// <param name="size">参数大小(默认：127)</param>
        /// <returns></returns>
        public static SqlParameter ToOutParam(this string parameterName, SqlDbType type, int size = 127)
        {
            parameterName = parameterName.StartsWith("@") ? parameterName : "@" + parameterName;
            SqlParameter param = new SqlParameter(parameterName, type, size);
            param.Direction = ParameterDirection.Output;
            return param;
        }

        /// <summary>
        /// 追加新的返回参数
        /// </summary>
        /// <param name="param">扩展参数集合</param>
        /// <param name="dbType">返回值SQLServer数据类型</param>
        public static void AppendReturnParam(this IList<SqlParameter> param, SqlDbType dbType = SqlDbType.Int)
        {
            SqlParameter retParam = new SqlParameter("ReturnValue", dbType);
            retParam.Direction = ParameterDirection.ReturnValue;
            param.Add(retParam);
        }
    }
}
